#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
Introduction to Programming in Java - An Interdisciplinary Approach

All book programs ported to Python by
Scott C. King (revisionx at {gee}ma1l <dot> c0m).

All program examples pass Pylint with a perfect 10.00 score.
Pylint:  http://www.pylint.org/


# Exercise 1.3.33 - Checksum

Syntax:
python isbn_checksum.py 123456789


Notes:
int(sys.argv[1]) == Integer.parseInt(args[0])

sys is a required import here in order to use command line arguments.
https://docs.python.org/2/tutorial/stdlib.html

'''

import sys


def main():
    ''' Given a 9-digit ISBN number, calculate trailing digit, print ISBN '''

    try:
        isbn = sys.argv[1]
        if len(isbn) != 9:
            raise IndexError
        print "Calculating ISBN checksum for {}.".format(isbn)
    except IndexError:
        print 'A 9-digit ISBN number is required.'
        print 'Syntax:  python isbn_checksum.py 123456789'
        sys.exit(0)

    total = 0

    for digit in range(0, 9):
        product = (10 - digit) * int(isbn[digit])
        total += product

    for num in range(1, 11):
        if (total + num) % 11 == 0:
            checksum = str(num)
            if checksum == '10':
                checksum = 'X'
            print 'Checksum found: {}'.format(checksum)
            break

    print "ISBN Number: ", isbn + checksum


if __name__ == '__main__':
    main()

